package com.qiezikaka.kaka.ui.scan;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.CountDownTimer;
import android.view.View;

import com.bumptech.glide.Glide;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qiezikaka.kaka.base.BaseActivity;
import com.qiezikaka.kaka.base.IPresenter;
import com.qiezikaka.kaka.common.Common;
import com.qiezikaka.kaka.databinding.ActivityScanCodeBinding;
import com.qiezikaka.kaka.databinding.ActivityStyleSingleBinding;
import com.qiezikaka.kaka.ui.StyleChoiceAllActivity;
import com.yzq.zxinglibrary.encode.CodeCreator;

/**
 * 扫码页面
 */
public class ScanCodeActivity extends BaseActivity {

    ActivityScanCodeBinding mBinding;

    @Override
    public View getLayout() {
        mBinding = ActivityScanCodeBinding.inflate(getLayoutInflater());
        return mBinding.getRoot();
    }

    @Override
    protected IPresenter getPresenter() {
        return null;
    }

    @Override
    protected void initEventAndData() {
        Intent intent = getIntent();
        String urlImg = intent.getStringExtra("url");
        String image = intent.getStringExtra("image");
        Bitmap qrBitmap = CodeCreator.createQRCode(urlImg, 400, 400, null);
        mBinding.ivQrcode.setImageBitmap(qrBitmap);

        mBinding.ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        Glide.with(this)
                .load(image)
                .into((RoundedImageView)mBinding.rivImage);
        initCountDown();
    }

    private CountDownTimer countDownTimer;
    private void initCountDown() {
        // 设置倒计时 10秒
        countDownTimer = new CountDownTimer(Common.CountDownTime, 1000) { // 10秒倒计时，每1秒更新一次
            @Override
            public void onTick(long millisUntilFinished) {
                // 可以更新UI，显示剩余时间
                // 例如：textView.setText("倒计时：" + millisUntilFinished / 1000);
                mBinding.tvCountDownTime.setText(""+ millisUntilFinished / 1000);
            }

            @Override
            public void onFinish() {
                // 倒计时结束后退出页面
                Intent intent = new Intent(ScanCodeActivity.this, StyleChoiceAllActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                finish(); // 可选，结束当前Activity
            }
        };
        countDownTimer.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownTimer != null) {
            countDownTimer.cancel(); // 确保倒计时被取消
        }
    }
}
